package com.nickstumpos.android.GmailWidgetPlus.Configure.OptionsList.options;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.ListView;

import com.nickstumpos.android.GmailWidgetPlus.Configure.OptionsList.OptionsList;
import com.nickstumpos.android.GmailWidgetPlus.Constants.GMWP_Constants;

public class AccountOptionList extends OptionsList {

	public AccountOptionList(final Context context,
			final int widgetId,
			final String title) {

		super(context, widgetId, title);
	}

	@Override
	protected void save() {

		final SharedPreferences.Editor prefs = this.getPrefs().edit();
		prefs.putString(GMWP_Constants.PREF_ACCOUNT_REF + this.getWidgetId(),
				this.getAa().getItem(this.getCheckedItemPosition() - 1));
		prefs.commit();
		this.setVisibility(View.GONE);
	}

	@Override
	protected void setupDialog() {

		final String name = this.getPrefs()
				.getString(GMWP_Constants.PREF_ACCOUNT_REF + this.getWidgetId(),
						null);
		int index = 1;
		int choice = -1;
		final Account[] accounts = AccountManager.get(this.getContext())
				.getAccountsByType(GMWP_Constants.GOOGLE_ACCOUNT_TYPE);
		for (final Account account : accounts) {
			this.getAa().add(account.name);
			if (name != null) {
				if (name.equals(account.name)) {
					choice = index;
				}
				index++;
			}
		}
		this.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		if (choice > 0) {
			this.setItemChecked(choice, true);
		} else {
			this.setItemChecked(1, true);
		}
	}
}
